import { 
  getUserItineraryBookkeepingListAllToTreeForUser,//获取用戶行程記賬列表
  postUserItineraryBookkeepingAddForUser,//添加用戶行程記賬
  postUserItineraryBookkeepingDeleteForUser,//刪除用戶行程記賬
  getUserItineraryPayerListAllForUser,//获取用戶行程支付人列表
  postUserItineraryPayerAddForUser,//添加用戶行程支付人
  postUserItineraryPayerDeleteForUser,//刪除用戶行程支付人
  getItineraryInfoByIdForUser,//用戶行程詳情
  getUserItineraryPayerListAllForTotalForUser,//获取用戶行程記賬合計
  getUserItineraryPaymentRecordListAllForUser,//获取支付记录
  postUserItineraryPaymentRecordEditForUser,//添加、修改用戶支付記錄
} from '../../api/home'
Page({
  data: {
    total: 9242,
    showFilter: false,
    showSelect:false,
    nameSelect:'餐飲',
    nameType:'food',
    nameIdType:1,
    selectedCategory: null,
    activeTab: 0,
    categories: [
      { id:1,type: "food", name: "餐飲", icon: "/pages/assets/image/foodItem.svg" },
      { id:2,type: "play", name: "景點", icon: "/pages/assets/image/playItem.svg" },
      { id:3,type: "shop", name: "購物", icon: "/pages/assets/image/shopItem.svg" },
      { id:4,type: "hotel", name: "住宿", icon: "/pages/assets/image/hotelItem.svg" },
      { id:5,type: "traffic", name: "交通", icon: "/pages/assets/image/trafficItem.svg" },
      { id:6,type: "other", name: "其他", icon: "/pages/assets/image/otherItem.svg" }
    ],
    expenses: [],
    settles: [],
    amount: '',
    showCursor: false,
    showKeyboard: false,
    keys: ['1','2','3','4','5','6','7','8','9','￥','0','.',],
    keys2: ['1','2','3','4','5','6','7','8','9','$','0','.',],
    priceUnit:'￥',
    delModal: false,//刪除
    timePopup:false,//事件彈框
    selectedTime:[],
    weekOptions: [], // ["6.29 星期二", "6.30 星期三", ...]
    hourOptions: [], // ["00", "01", "02", ...]
    minuteOptions: [], // ["00", "01", "02", ...]
    showAddPopup:false,//添加支付人
    showSelectPopup:false,//選擇支付人
    newFolderName: '',
    newFolderName2: '',
    selectedFolder: '',
    folderList: [], // 模擬的收藏夾
    itinerary_id:'',//行程id
    itinerary_payer_id:'',//支付人id
    name:'',//刪除顯示
    remark:'',//添加備注
    day_num:'',//天数
    time:'',//时间
    itineraryDetail:{},
    dateRange:'',
    dayNum:'',
    isScrolling: false, // 是否正在滚动
  },
  onLoad(e){
    this.setData({
      itinerary_id:e.itinerary_id
    })
    this.getData()
    this.getPayList()
    this.initPickerData();
  },
  async addName(){
    const res = await postUserItineraryPayerAddForUser({
      itinerary_id:this.data.itinerary_id,
      name:this.data.newFolderName
    })
    this.setData({
      newFolderName2:this.data.newFolderName,
      newFolderName:'',
      itinerary_payer_id:res.data.info.itinerary_payer_id
    })
    wx.showToast({
      title: '添加成功',
    })
  },
  openClose(e){
    const id = e.currentTarget.dataset.id
    const name = e.currentTarget.dataset.name
    this.setData({
      itinerary_payer_id:id,
      name,
      collectModal: true,
    }) 
  },
  async getData() {
    const res = await getUserItineraryBookkeepingListAllToTreeForUser({
      itinerary_id: this.data.itinerary_id
    });
  
    const list = res.data.list || [];
    const allChildren = list.flatMap(item => item.child || []);

    // 累加 sum_amount（确保是数字）
    const total = list.reduce((acc, item) => acc + Number(item.sum_amount || 0), 0);
  
    // 取天数
    const dayNum = list.length;
  
    // 取起止日期
    let dateRange = '';
    if (dayNum > 0) {
      const firstDate = list[0].date || '';
      const lastDate = list[dayNum - 1].date || '';
      dateRange = `${firstDate} - ${lastDate}`;
    }
  
    this.setData({
      total,
      dayNum,
      dateRange,
      expenses:allChildren
    });
  },
  async getPayList(){
    const res = await getUserItineraryPaymentRecordListAllForUser({
      itinerary_id:this.data.itinerary_id
    })
    this.setData({
      settles:res.data.list
    })
  },
  payAddClick(){
    this.setData({
      showAddPopup:true
    })
  },
  // 輸入新收藏夾名稱
  onInputFolderName(e) {
    this.setData({ 
      newFolderName: e.detail.value,
      selectedFolder:''
     });
  },    

  // 打開選擇收藏夾
  async openSelectPopup() {
    const res = await getUserItineraryPayerListAllForUser({
      itinerary_id:this.data.itinerary_id
    })
    this.setData({ 
      showSelectPopup: true,
      folderList:res.data.list
     });
  },    

  // 關閉選擇收藏夾
  closeSelectPopup() {
    this.setData({ showSelectPopup: false });
  },

  // 選擇收藏夾
  chooseFolder(e) {
    this.setData({
      selectedFolder: e.currentTarget.dataset.name,
      itinerary_payer_id:e.currentTarget.dataset.id,
      newFolderName: '',
      showSelectPopup: false,
      showAddPopup: false,
    });
  },

  // 關閉添加支付人彈框
  closePayPopup() {
    this.setData({ 
      showAddPopup: false ,
      newFolderName: '',
    });
  },

  // 確認添加
  confirmAdd() {
    const { newFolderName, selectedFolder } = this.data;
    if (!newFolderName && !selectedFolder) {
      wx.showToast({ title: '請輸入或選擇收藏夾', icon: 'none' });
      return;
    }
    if(selectedFolder){
      this.setData({
        showAddPopup: false,
      })
      return
    }
    this.addName()
    
    this.setData({
      showAddPopup: false,
      // newFolderName:'',
      // selectedFolder:''
    })
  },
  onDayPickerStart() {
    this.setData({
      isScrolling: true
    })
  },

  // 滚动结束
  onDayPickerEnd() {
    this.setData({
      isScrolling: false
    })
  },
  // 確認時間
  selectTimeClick() {
    if (this.data.isScrolling) {
      wx.showToast({
        title: '請等待滾動停止',
        icon: 'none'
      })
      return
    }

  const { selectedTime } = this.data;
  if (!selectedTime) return;

  // 提取 day_num
  const dayMatch = selectedTime.week.match(/DAY (\d+)/);
  const day_num = dayMatch ? parseInt(dayMatch[1], 10) : null;

  // 拼接时间字符串
  const time = `${selectedTime.hour}:${selectedTime.minute}`;

  console.log('day_num:', day_num, 'time:', time);

  // 这里你可以保存到 data 或提交接口
  this.setData({
    day_num,
    time,
    timePopup: false
  });
  },
  selectEnd(e) {
    const val = e.detail.value; // [dayIndex, hourIndex, minuteIndex]
    const week = this.data.weekOptions[val[0]];
    const hour = this.data.hourOptions[val[1]];
    const minute = this.data.minuteOptions[val[2]];

    console.log('當前選擇：', week, hour, minute);

    // 保存为对象
    this.setData({
      selectedTime: {
        week,
        hour,
        minute
      },
      // 如果你需要拼接成 "YYYY-MM-DD HH:MM" 格式
      selectedTimeString: `${week} ${hour}:${minute}`
    });
  },
  // 關閉時間彈框
  closePopup(){
    this.setData({
      timePopup:false,
      collectModal:false
    })
  },
  
  // 選擇器滾動事件
  selectStart(e) {
  },
  // 初始化選擇器數據
  async initPickerData() {
    const res = await getItineraryInfoByIdForUser({
      itinerary_id: this.data.itinerary_id
    });
    const days = res.data.list_item.map(item => `DAY ${item.day_num}`);

    // 小時
    const hours = [];
    for (let i = 0; i < 24; i++) {
      hours.push(i < 10 ? '0' + i : '' + i);
    }

    // 分鐘
    const minutes = [];
    for (let i = 0; i < 60; i++) {
      minutes.push(i < 10 ? '0' + i : '' + i);
    }

    // 設置默認索引值 [第0天, 0小時, 0分鐘]
    const defaultValue = [0, 0, 0];

    this.setData({
      itineraryDetail:res.data.info,
      weekOptions: days,
      hourOptions: hours,
      minuteOptions: minutes,
      selectEndValue: defaultValue, // picker-view 默認顯示的值
      selectedTime: {
        week: days[0],
        hour: hours[0],
        minute: minutes[0]
      },
      selectedTimeString: `${days[0]} ${hours[0]}:${minutes[0]}`
    });
  },

  showCustomKeyboard() {
    this.setData({
      showKeyboard: true,
      showCursor: true
    })
  },

  onKeyTap(e) {
    const val = e.currentTarget.dataset.val;
    if(val=='￥'){
      this.setData({ 
        priceUnit:'$'
       });
       return
    }
    if(val=='$'){
      this.setData({ 
        priceUnit:'￥'
       });
       return
    }

    let amount = this.data.amount || "";

    // 小数点只允许出现一次
    if (val === '.' && amount.includes('.')) {
      return;
    }
  
    // 拼接金额
    amount = amount + val;
    this.setData({ amount });
  },

  onDelete() {
    let amount = this.data.amount.slice(0, -1);
    this.setData({ amount });
  },
  onhide(){
    this.setData({
      showKeyboard: false,
      showCursor: false,
    });
  },
  // 监听输入
  onRemarkInput(e) {
    this.setData({
      remark: e.detail.value
    })
  },
  async onConfirm() {
    if(!this.data.itinerary_payer_id){
      wx.showToast({
        title: '請選擇支付人',
        icon:'none'
      })
      return
    }
    if(!this.data.day_num){
      wx.showToast({
        title: '請選擇日期',
        icon:'none'
      })
      return
    }
    if(!this.data.amount){
      wx.showToast({
        title: '請輸入金額',
        icon:'none'
      })
      return
    }
    const res = await postUserItineraryBookkeepingAddForUser({
      itinerary_id:this.data.itinerary_id,
      itinerary_payer_id:this.data.itinerary_payer_id,
      title:this.data.remark,
      amount:this.data.amount,
      type:this.data.nameIdType,
      day_num:this.data.day_num,
      time:this.data.time,
  })
    wx.showToast({
      title: '添加成功',
    })
    this.getData()
    this.getPayList()
    this.setData({
      showKeyboard: false,
      showCursor: false,
      amount:'',
      remark:''
    });
  },

  closeModal(){
    this.setData({
      delModal:false
    });
  },
  async confirmDelete(){
    const res = await postUserItineraryPayerDeleteForUser({
      itinerary_id:this.data.itinerary_id,
      itinerary_payer_id:this.data.itinerary_payer_id
    })
    this.openSelectPopup()
    wx.showToast({
      title: '刪除成功',
    })
    this.setData({
      collectModal:false
    });
  },
  openFilter(e) {
    const date = e.currentTarget.dataset.date
    this.setData({
      showFilter: true, 
      currentFilterDate: date // 記錄當前點開的日期
    })
  }, 

  closeFilter() {
    this.setData({ 
      showFilter: false,
      showSelect: false,
     });  
  },
  allCategory(){
    this.setData({ showFilter: false });
  },
  selectCategory(e) {
    this.setData({ showFilter: false });
  }, 
  showItemSelect(){
    this.setData({  
      showSelect: true,
     });
  },
  showDaySelect(){
    this.setData({  
      timePopup: true,
     });
  },
  selectClick(e){
    const name = e.currentTarget.dataset.name
    const type = e.currentTarget.dataset.type
    const id = e.currentTarget.dataset.id
    this.setData({  
      showFilter: false,
      showSelect: false,
      nameSelect:name,
      nameType:type,
      nameIdType:id
     });
  },
  switchTab(e) {
    this.setData({
      activeTab: Number(e.currentTarget.dataset.index)
    });
  },
  // 切換結清狀態
  async statusClick(e) {
    const index = e.currentTarget.dataset.index;
    let settles = [...this.data.settles];
    settles[index].status = settles[index].status==1?0:1;  // 取反
    settles[index].itinerary_id = this.data.itinerary_id
    const res = await postUserItineraryPaymentRecordEditForUser(settles[index])
    this.setData({ settles });
  },
  dianClick(){
    wx.navigateTo({
      url: `/pages/transaction/billList/billList?itinerary_id=${this.data.itinerary_id}`,
    })
  }
});
